{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>E-M-WEB</title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <style>
        {% include 'css/resetcss.css' %}
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-size: 0.8rem;
        }

        .container {
            width: 390px;
            padding: 30px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            display: flex;
            align-items: center;
            justify-content: center;
        }

        label {
            width: 300px;
            margin-bottom: 15px;
            display: flex block;
            align-items: center;
            justify-content: center;
        }

        input {
            padding: 15px;
            border: none;
            border-bottom: 1px #ccc solid;
            margin-bottom: 10px;
        }

        .input-group {
            width: 100%;
        }

        #checkcode {
            width: 50%;
            left: 0;
            margin-left: -15px;
            /* Add additional styling for checkcode */
        }

        .checkcodebox {
            position: relative;
            display: flex inline;
            height: 40px;
            width: 100px;
            left: 15px;
            top: -5px;
            border: 1px rgba(76, 175, 80, 0.5) solid;
            align-items: center;
            justify-content: center;
        }

        input[type="submit"] {
            background-color: rgba(76, 175, 80, 0.8);
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            cursor: pointer;
            margin-top: 10px;
            margin-bottom: -10px;
        }
    </style>
    <script src="{% static 'js/alert.js' %}"></script>
    <script src="{% static 'js/validForm.js' %}"></script>
</head>
<body>
<div class="container">
{#    <div><img src="#" alt="logo"/>LOGO</div>#}
    <form method="POST" action="{% url 'index' %}" name="my_form" id="my_form">
        {% csrf_token %}
        <label>
            <input type="text" class="input-group" id="username" name="username" max="20"
                   placeholder="请输入用户名/手机号">
        </label>
        <label>
            <input type="password" class="input-group" id="password" name="password" max="20"
                   placeholder="请输入密码">
        </label>
        <label>
            <input type="text" name="checkcode" id="checkcode" placeholder="请输入验证码">
            <div class="checkcodebox" id="checkcodeshow" onclick="updateCheckCode()">验证码显示</div>
        </label>
        <label>
            <input type="submit" value="提 交" class="input-group" id="submitButton">
        </label>
    </form>
</div>
</body>

<script>
    onFocusInputNotEmpty("username");
    onFocusInputNotEmpty("password");
    onFocusInputNotEmpty("checkcode");
    function validFormSubmit() {
        return onSubmitInputNotEmpty(["username","password","checkcode"])
    }
</script>

{#生成验证码并校验#}
<script>
    let checkCodeResult = {
        checkCode: null,
        result: null
    };

    // 生成随机的可计算算式
    function generateCheckCode() {

        const operators = ['+', '-', '*'];
        const operator = operators[Math.floor(Math.random() * operators.length)];

        const num1 = Math.floor(Math.random() * 10);
        const num2 = Math.floor(Math.random() * 10);

        let result;
        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num1 / num2;
                break;
        }

        const checkCode = num1 + ' ' + operator + ' ' + num2 + ' = ?';
        checkCodeResult = {
            checkCode: checkCode,
            result: result
        }

        return checkCodeResult;
    }

    // 验证算式结果
    function validateCheckCode() {
        let valid_result = false
        const inputCheckCode = document.getElementById('checkcodeshow').innerText;
        const userInput = document.getElementById('checkcode').value;

        const checkCode = checkCodeResult;
        console.log("用户输入-->", userInput)
        console.log("验证码-->", checkCode)
        if (userInput === String(checkCode.result)) {
            // 算式结果验证通过
            // 可以在此处添加你的逻辑代码
            valid_result = true
        } else {
            // 算式结果验证失败
            // 可以在此处添加你的逻辑代码
            alert_error("验证码错误")
        }
        return valid_result
    }

    // 更新验证码显示并添加事件处理程序
    function updateCheckCode() {
        const checkCode = generateCheckCode();
        const checkCodeElement = document.getElementById('checkcodeshow');
        checkCodeElement.innerText = checkCode.checkCode;
    }

    // 初始化
    updateCheckCode();
</script>

{#提交表单逻辑#}
<script>
    // 获取表单元素
    const form = document.getElementById('my_form');

    // 表单提交事件处理函数
    function handleSubmit(event) {
        event.preventDefault(); // 阻止表单的默认提交行为
        if (validateForm()) {
            submitForm(event)// 表单赋值
        }
    }

    // 表单校验函数
    function validateForm() {
        // 执行表单校验逻辑，返回校验结果
        // 如果校验通过，返回 true；否则返回 false
        return validFormSubmit() && validateCheckCode()
    }

    // 绑定提交按钮的点击事件
    {#const submitButton = document.getElementById('submitButton');#}
    submitButton.addEventListener('click', handleSubmit);

    function submitForm(event) {
        // 发送AJAX请求到 /api/login 进行校验
        fetch('{% url 'login' %}', {
            method: 'POST',
            body: new FormData(form)
        })
            .then(response => response.json())
            .then(data => {
                // 校验成功后提交表单到action页面
                if (data.code === 0) {
                    alert_success(data.msg)
                    sessionStorage.setItem('USERSESSION', data.data);
                    form.submit();
                } else {
                    // 校验失败，显示错误信息
                    alert_error(data.msg)
                    console.log(data)
                }
            })
            .catch(error => {
                // 处理请求错误
                alert_error("登录异常,请联系管理员 !!!")
                console.error('Error:', error);
            });
    }
</script>

</html>
